import * as echarts from 'echarts'

export default {
  created () {
    this._chartMap = new Map()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy () {
    if (this._chartMap.size) {
      this.$disposeCharts()
      window.removeEventListener('resize', this.resizeCharts)
    }
  },
  methods: {
    resizeCharts () {
      clearTimeout(this._resizeTimer)
      this._resizeTimer = setTimeout(() => {
        for (const instance of this._chartMap.values()) {
          instance.resize()
        }
      }, 100)
    },
    $getChartInstance (chartId) {
      if (!this._chartMap.has(chartId)) {
        const instance = echarts.init(document.querySelector(chartId))
        this._chartMap.set(chartId, instance)
      }
      return this._chartMap.get(chartId)
    },
    $disposeCharts () {
      for (const [chartId, instance] of this._chartMap.entries()) {
        instance.dispose()
        this._chartMap.delete(chartId)
      }
    }
  }
}
